from django.db import models
from django.contrib.auth.models import AbstractUser
from django.core.validators import MinValueValidator, RegexValidator


class User(AbstractUser):
    phone = models.CharField(max_length=15, unique=True, null=True,
                             validators=[RegexValidator(r'^[0-9]+$')])
    last_login_ip = models.GenericIPAddressField(null=True)
    avatar = models.URLField(null=True)
    is_active = models.BooleanField(default=True)

    groups = models.ManyToManyField(
        'auth.Group',
        related_name='shop_user_set',
        blank=True,
        help_text='用户所属组'
    )
    user_permissions = models.ManyToManyField(
        'auth.Permission',
        related_name='shop_user_set',
        blank=True,
        help_text='用户特定权限'
    )


class ProductCategory(models.Model):
    name = models.CharField(max_length=50, unique=True)
    parent = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
    sort_order = models.IntegerField(default=0)
    path = models.CharField(max_length=255, blank=True, editable=False)
    meta_title = models.CharField(max_length=100, blank=True)
    meta_description = models.TextField(blank=True)

    class Meta:
        db_table = 'product_categories'
        ordering = ['sort_order']
        verbose_name = '商品分类'

    def save(self, *args, **kwargs):
        if self.parent:
            self.path = f"{self.parent.path}/{self.parent_id}"
        super().save(*args, **kwargs)


class Product(models.Model):
    STATUS_CHOICES = [
        ('draft', '草稿'),
        ('published', '已上架'),
        ('archived', '已归档')
    ]

    name = models.CharField(max_length=100)
    sku = models.CharField(max_length=50, unique=True)
    category = models.ForeignKey(ProductCategory, on_delete=models.PROTECT)
    price = models.DecimalField(max_digits=10, decimal_places=2,
                                validators=[MinValueValidator(0.01)])
    cost_price = models.DecimalField(max_digits=10, decimal_places=2, null=True)
    stock = models.PositiveIntegerField(default=0)
    sales = models.PositiveIntegerField(default=0)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
    main_image = models.URLField(null=True)
    description = models.TextField(null=True)
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL,
                                   null=True, related_name='created_products')
    updated_by = models.ForeignKey(User, on_delete=models.SET_NULL,
                                   null=True, related_name='updated_products')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'products'
        indexes = [
            models.Index(fields=['name']),
            models.Index(fields=['category', 'status']),
            models.Index(fields=['sku']),
        ]
        verbose_name = '商品'

    def publish(self):
        if self.status == 'draft':
            self.status = 'published'
            self.save()


class Order(models.Model):
    STATUS_CHOICES = [
        ('pending', '待支付'),
        ('paid', '已支付'),
        ('shipped', '已发货'),
        ('completed', '已完成'),
        ('cancelled', '已取消')
    ]

    PAYMENT_METHODS = [
        ('alipay', '支付宝'),
        ('wechat', '微信支付'),
        ('bank', '银行转账')
    ]

    user = models.ForeignKey(User, on_delete=models.PROTECT)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending')
    payment_method = models.CharField(max_length=20, choices=PAYMENT_METHODS, null=True)
    shipping_address = models.TextField()
    tracking_number = models.CharField(max_length=50, null=True)
    cancel_reason = models.TextField(null=True)
    total_amount = models.DecimalField(max_digits=12, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'orders'
        indexes = [
            models.Index(fields=['user', 'status']),
            models.Index(fields=['created_at']),
        ]
        verbose_name = '订单'


class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items')
    product = models.ForeignKey(Product, on_delete=models.PROTECT)
    quantity = models.PositiveIntegerField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    refund_status = models.CharField(max_length=20, default='none')
    reviewed = models.BooleanField(default=False)

    class Meta:
        db_table = 'order_items'
        verbose_name = '订单明细'
